<script lang="ts" setup>
import { debounce } from "@pureadmin/utils";
import * as echarts from "echarts";
import { defineProps, onMounted, onUnmounted, ref, watchEffect } from "vue";
const props = defineProps<{
  data: any;
  color: string[];
}>();
const pieChartRef = ref();
const charts = ref([]);
let pieChart = null;
const initPieChart = async () => {
  if (!pieChartRef.value) {
    return;
  }
  // 2、图表渲染
  const chartDom = pieChartRef.value;
  if (!pieChart) {
    pieChart = echarts.init(chartDom, null, { renderer: "svg" });
  }
  let option;

  option = {
    tooltip: {
      show: false
    },
    devicePixelRatio: window.devicePixelRatio || 2,
    grid: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    },
    legend: {
      show: false
    },
    color: props.color,
    series: [
      {
        name: "今日任务",
        type: "pie",
        radius: ["60%", "82%"],
        avoidLabelOverlap: false,
        padAngle: 1,
        itemStyle: {
          borderRadius: 0
        },
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: false,
            fontSize: 14,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: props.data
      }
    ]
  };
  option && pieChart.setOption(option);
  if (!charts.value.includes(pieChart)) {
    charts.value.push(pieChart);
  }
};
// 处理窗口大小变化
const handleResize = debounce(() => {
  charts.value.forEach(chart => {
    chart.resize();
  });
}, 60);
watchEffect(() => {
  initPieChart();
});
onMounted(() => {
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  charts.value.forEach(chart => {
    chart.dispose();
  });
});
</script>
<template>
  <div class="chart-container">
    <div ref="pieChartRef" class="chart-pie"></div>
    <div class="pie-content">
      {{ data[0].value }}
    </div>
  </div>
</template>
<style lang="scss" scoped>
.chart-container {
  width: 48rpx;
  height: 48rpx;
  position: relative;
  margin: 0 auto;
}
.chart-pie {
  width: 48rpx;
  height: 48rpx;
  position: absolute;
  top: 0;
  left: 0;
}
.pie-content {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  font-size: 14rpx;
  font-family: AlibabaPuHuiTiM;
  color: rgba(255, 255, 255, 0.9);
  line-height: 20rpx;
}
</style>
